/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util.httpclient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.enfry.common.util.Ids;
import com.enfry.common.util.array.ConvertUtils;
import com.enfry.common.util.constants.HttpConstants;
import com.enfry.common.util.validate.Validates;

/**
 * 带session请求
 * 
 * @Title com.enfry.util.httpclient.HttpWebReq
 * @author Penghu
 * @date 2018年7月12日
 */
public class HttpWebReq implements HttpConstants {

	private static Logger log = LoggerFactory.getLogger(HttpWebReq.class);

	private final static int messageTimeout = 45;
	private final static int connectionTimeout = 45;

	/**
	 * 发送请求类
	 * 
	 * @param url 请求地址
	 * @param param 请求参数 form提交格式
	 * @param sessionId 请求sessionId
	 * @param xFFIp XFF格式IP
	 * @return
	 * @return String
	 * @throws
	 * @author Penghu
	 * @date 2018年7月12日
	 */
	public static String sendWebReq(String url, String param, String sessionId, String xFFIp) {
		String reuqestId = Ids.uuid();
		log.info("请求地址(" + reuqestId + "):" + url + ",请求IP:" + xFFIp);
		log.info("发送报文(" + reuqestId + "):" + param);
		HttpPost client = new HttpPost(url);
		client.setQueryString(param, _UTF_8_);
		client.setMimeType(_APPLICATION_X_WWW_FORM_);
		client.addRequestProperty(_X_FORWARDED_FOR_, getProxyIpAll(xFFIp));
		if (Validates.isNotEmpty(sessionId)) {
			client.addRequestProperty("Cookie", "JSESSIONID=" + sessionId + ";SESSION=" + sessionId);
		}
		client.setConnectTimeout(connectionTimeout);
		client.setReadTimeout(messageTimeout);
		client.execute();

		int responseStatus = client.getResponseStatus();
		String responseText = client.getResponseText();
		log.info("接收报文(" + reuqestId + ")：" + responseText);
		if (responseStatus != 200) {
			log.error("请求接口网络异常(" + reuqestId + ")：" + responseText);
			return null;
		}
		return responseText;
	}

	public static String getSessionId(String url, String param, String sessionId, String xFFIp) {
		String reuqestId = Ids.uuid();
		log.info("请求地址(" + reuqestId + "):" + url + ",请求IP:" + xFFIp);
		log.info("发送报文(" + reuqestId + "):" + param);
		HttpPost client = new HttpPost(url);
		client.setQueryString(param, _UTF_8_);
		client.addRequestProperty("http.protocol.cookie-policy", "compatibility");
		client.setMimeType(_APPLICATION_X_WWW_FORM_);
		client.addRequestProperty(_X_FORWARDED_FOR_, getProxyIpAll(xFFIp));
		if (Validates.isNotEmpty(sessionId)) {
			client.addRequestProperty("Cookie", "JSESSIONID=" + sessionId + ";SESSION=" + sessionId);
		}

		client.setConnectTimeout(connectionTimeout);
		client.setReadTimeout(messageTimeout);
		client.execute();

		String setCookie = client.getResponseProperty("set-cookie");
		if (Validates.isNotEmpty(setCookie)) {
			List<String> cookieList = ConvertUtils.toStringList(setCookie, ";");
			String jsessionId = UrlUtils.get(cookieList.get(0), "JSESSIONID");
			if (Validates.isNotEmpty(jsessionId)) {
				return jsessionId;
			}
		}

		return sessionId;
	}

	/**
	 * 拼接代理IP，XFF 的内容由「英文逗号 + 空格」： client, proxy1, proxy2
	 * 
	 * @param ip
	 * @return
	 * @return String
	 * @throws
	 * @author Penghu
	 * @date 2018年7月12日
	 */
	private static String getProxyIpAll(String ip) {
		try {
			InetAddress address = InetAddress.getLocalHost();
			String hostAddress = address.getHostAddress();// 192.168.0.121
			if (Validates.isEmpty(ip)) {
				return hostAddress;
			} else if (Validates.isNotEmpty(hostAddress)) {
				ip = ip + ", " + hostAddress;
			}

		} catch (UnknownHostException e) {
			e.printStackTrace();
			return ip;
		}

		return ip;
	}

}
